package cn.yzgy.yzgyoa.ucenter.service.impl;

import cn.yzgy.yzgyoa.ucenter.dto.SysDepartmentDTO;
import cn.yzgy.yzgyoa.ucenter.entity.SysDepartment;
import cn.yzgy.yzgyoa.ucenter.entity.UserInfoDetail;
import cn.yzgy.yzgyoa.ucenter.mapper.SysDepartmentMapper;
import cn.yzgy.yzgyoa.ucenter.service.ISysDepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yqsen
 * @since 2021-06-03
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {

    @Override
    public IPage<SysDepartmentDTO> getAllDepartment(Page<SysDepartmentDTO> departmentPage) {
        return baseMapper.getAllDepartment(departmentPage);
    }

    @Override
    public List<SysDepartmentDTO> getDepartmentTree() {
        List<SysDepartmentDTO> departmentTree = baseMapper.getDepartmentTree();
        for (SysDepartmentDTO sysDepartmentDTO : departmentTree) {
            sysDepartmentDTO.setTitle(sysDepartmentDTO.getName());
            sysDepartmentDTO.setCheckArr("0");
        }
        return departmentTree;
    }

    @Override
    public boolean addDepartment(SysDepartment queryDto, UserInfoDetail currentUser) {

        SysDepartment sysDepartment = new SysDepartment().selectOne(new QueryWrapper<SysDepartment>().lambda()
                                        .eq(SysDepartment::getParentId, queryDto.getParentId())
                                        .eq(SysDepartment::getName, queryDto.getName()));
        if(sysDepartment!=null){
            return false;
        }
        String newId = getNewId(queryDto);
        if (newId == null) {
            newId = queryDto.getParentId() + "01";
        }else{
            newId= new BigDecimal(newId).add(new BigDecimal(1)).toString();
        }
        queryDto.setId(Integer.parseInt(newId)).setCreateBy(currentUser.getUid().toString());

        return queryDto.insert();
    }

    @Override
    public boolean updateDepartment(SysDepartment queryDto, UserInfoDetail currentUser) {
        return queryDto.setUpdateBy(currentUser.getUid().toString())
                .setUpdateTime(LocalDateTime.now())
                .updateById();
    }

    @Override
    public boolean deleteDepartment(Integer id) {
        return new SysDepartment().delete(new UpdateWrapper<SysDepartment>()
                    .lambda().likeRight(SysDepartment::getId, id));
    }

    private String getNewId(SysDepartment sysDepartment) {
        return baseMapper.getNewId(sysDepartment.getParentId());
    }
}
